package com.dts.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtUtil {
    private static final String SECRET_KEY = "jslfjs*747**$%#^H"; // 密钥

    public static String generateToken(String username) {
        Date start = new Date();
        //一小时有效时间
        long currentTime = System.currentTimeMillis() + 60* 60 * 1000;
        Date end = new Date(currentTime);
        String token = "";

        token = JWT.create().withAudience(username).withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(SECRET_KEY));
        return token;

    }

    public static String validateToken(String token) {
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
        try {
            DecodedJWT verify = jwtVerifier.verify(token);
            return verify.getAudience().get(0);
        } catch (JWTVerificationException e) {
            return null;
        }
    }
}